<template>
  <el-card class="spu-card">
    <el-form
      label-width="100px"
      ref="spuFormRef"
      :model="spuFormData"
      :rules="spuFormRules"
    >
      <el-form-item label="SPU名称" prop="spuName">
        <el-input placeholder="SPU名称" v-model="spuFormData.spuName" />
      </el-form-item>

      <el-form-item label="品牌" prop="tmId">
        <el-select placeholder="请选择品牌" v-model="spuFormData.tmId">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="tm in allTrademarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="SPU描述" prop="description">
        <el-input
          type="textarea"
          placeholder="SPU描述"
          :rows="2"
          v-model="spuFormData.description"
        />
      </el-form-item>
      <!-- //上传图片 -->
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          v-model:file-list="spuFormData.spuImageList"
          :action="UPLOAD_URL_PREFIX + '/admin/product/fileUpload'"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload"
          :limit="MAX_LIMIT_LENGTH"
          :on-success="handleSuccess"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过200kb</div>
          </template>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select v-model="selectedSaleAttr">
          <el-option
            :label="attr.name"
            :value="`${attr.id}:${attr.name}`"
            v-for="attr in filterSpuAttrList"
            :key="attr.id"
          ></el-option>
        </el-select>
        <el-button
          :icon="Plus"
          type="primary"
          class="spu-btn"
          :disabled="!selectedSaleAttr"
          @click="addSpuAttr"
          >添加销售属性</el-button
        >
        <el-table border :data="spuFormData.spuSaleAttrList" class="spu-table">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="60"
          ></el-table-column>
          <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
          <el-table-column label="属性值名称列表">
            <template v-slot="{ row }">
              <el-tag
                v-for="(tag, index) in row.spuSaleAttrValueList"
                :key="tag.saleAttrValueName"
                class="mx-1"
                closable
                :disable-transitions="false"
                @close="handleClose(row, index)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.isEdit"
                placeholder="请输入属性值"
                class="spu-input"
                ref="inputRef"
                v-model="saveAttrValue"
                @blur="showBtnAndTag(row)"
                @keyup.enter="showBtnAndTag(row)"
              />
              <el-button
                v-else
                :icon="Plus"
                @click="showInput(row)"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ $index }">
              <el-tooltip content="删除销售属性" placement="top" effect="light">
                <el-button
                  :icon="Delete"
                  type="danger"
                  size="small"
                  @click="removeSaleAttr($index)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="goSpuList">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "SaveOrUpdateSpu",
};
</script>

<script lang="ts" setup>
import { Plus, Delete } from "@element-plus/icons-vue";
import { ref, onMounted, reactive, computed, nextTick } from "vue";
import { getAllTrademarkListApi } from "@/api/product/trademark";
import {
  getAllSpuListApi,
  saveSpuApi,
  getSpuSaleAttrListApi,
  getSpuImageListApi,
  updateSpuApi,
} from "@/api/product/spu";
import type {
  getAllSpuList,
  SpuFormData,
  SpuImageList,
  SpuSaleAttrList,
} from "@/api/product/model/spuModel";
import type { getAllTrademarkList } from "@/api/product/model/trademarkModel";
import type { UploadProps, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { useCategoryStore } from "@/stores/category";
const categoryStore = useCategoryStore();
const emit = defineEmits(["showSpuList"]);

const selectedSaleAttr = ref("");
const saveAttrValue = ref("");
const inputRef = ref();

const props = defineProps<{
  spu: SpuFormData;
}>();
const spuFormRef = ref();
const spuFormData = reactive<SpuFormData>(props.spu);

const addSpuAttr = () => {
  const [id, name] = selectedSaleAttr.value.split(":");
  spuFormData.spuSaleAttrList.push({
    baseSaleAttrId: +id,
    saleAttrName: name,
    spuSaleAttrValueList: [],
    isEdit: false,
  });
  selectedSaleAttr.value = "";
};
const filterSpuAttrList = computed(() => {
  return allSpuList.value.filter((baseAttr) => {
    return !spuFormData.spuSaleAttrList.some(
      (saleAttr) => saleAttr.baseSaleAttrId === baseAttr.id
    );
  });
});

//点击按钮进入编辑模式
const showInput = async (row: SpuSaleAttrList) => {
  row.isEdit = true;
  await nextTick();
  inputRef.value.focus();
};
//点击INPUT添加Tag并进入显示模式
const showBtnAndTag = (row: SpuSaleAttrList) => {
  if (saveAttrValue.value) {
    row.spuSaleAttrValueList.push({
      baseSaleAttrId: row.baseSaleAttrId,
      saleAttrValueName: saveAttrValue.value,
    });
  }
  saveAttrValue.value = "";
  row.isEdit = false;
};
//展示属性值并处理点击删除
const handleClose = (row: SpuSaleAttrList, index: number) => {
  row.spuSaleAttrValueList.splice(index, 1);
};

//点击删除该行属性
const removeSaleAttr = (index: number) => {
  spuFormData.spuSaleAttrList.splice(index, 1);
};

//返回属性列表页
const goSpuList = () => {
  emit("showSpuList", 1);
};
/***********上传图片功能************/
const UPLOAD_URL_PREFIX = import.meta.env.VITE_API_URL;
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const MAX_LIMIT_LENGTH = 2;
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url as string;
  dialogVisible.value = true;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imageTypes = ["image/jpeg", "image/jpg", "image/png"];
  if (!imageTypes.includes(rawFile.type)) {
    ElMessage.error("上传的图片必须是jpg或png格式!");
    return false;
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("上传的图片不能超过200kb!");
    return false;
  }
  return true;
};
const isDisplay = computed(() => {
  return spuFormData.spuImageList.length < MAX_LIMIT_LENGTH
    ? "inline-flex"
    : "none";
});
const handleSuccess = () => {
  if (spuFormData.spuImageList.length === 1) {
    spuFormRef.value?.clearValidate(["spuImageList"]);
  }
};

const spuSaleAttrListValidator = (rule: any, value: any, callback: any) => {
  if (!value.length) {
    callback(new Error("请至少添加一个销售属性"));
    return;
  }
  if (!value.every((saleAttr) => saleAttr.spuSaleAttrValueList.length)) {
    callback(new Error("每个销售属性至少添加一个属性值"));
    return;
  }
  callback();
};

const spuFormRules = reactive<FormRules>({
  spuName: [{ required: true, message: "请输入SPU名称", trigger: "blur" }],
  tmId: [{ required: true, message: "请选择SPU品牌", trigger: "change" }],
  description: [{ required: true, message: "请输入SPU描述", trigger: "blur" }],
  spuImageList: [{ required: true, message: "请上传SPU图片" }],
  spuSaleAttrList: [
    {
      required: true,
      // 自定义校验规则
      validator: spuSaleAttrListValidator,
    },
  ],
});

const submitForm = async () => {
  await spuFormRef.value?.validate();
  const data = {
    ...spuFormData,
    timId: spuFormData.timId as number,
    spuImageList: spuFormData.spuImageList.map((img) => {
      return {
        imgName: img.name,
        imgUrl: img.response ? (img.response as any).data : img.url,
      };
    }),
    category3Id: categoryStore.category3Id as number,
  };
  if (spuFormData.id) {
    await updateSpuApi(data);
  } else {
    await saveSpuApi(data);
  }

  ElMessage.success(`${spuFormData.id ? "更新" : "添加"}添加SPU成功`);

  goSpuList();
};
/***************************/
//获取组件实例

const allSpuList = ref<getAllSpuList>([]);
const allTrademarkList = ref<getAllTrademarkList>([]);
//请求品牌数据
onMounted(async () => {
  allTrademarkList.value = await getAllTrademarkListApi();
});
//请求基础属性数据
onMounted(async () => {
  allSpuList.value = await getAllSpuListApi();
});

onMounted(async () => {
  const { id } = spuFormData;
  if (id) {
    spuFormData.spuSaleAttrList = await getSpuSaleAttrListApi(id);
  }
});
onMounted(async () => {
  const { id } = spuFormData;
  if (id) {
    const res = await getSpuImageListApi(id);
    spuFormData.spuImageList = res.map((item) => {
      return {
        name: item.imgName,
        url: item.imgUrl,
      };
    });
  }
});
</script>

<style scoped>
.spu-table {
  margin: 10px 0;
}
.spu-btn {
  margin-left: 10px;
}
.spu-card :deep(.el-upload) {
  display: v-bind(isDisplay);
}
.spu-input {
  width: 150px;
}
</style>
